package com.yicong.ants.scenic

import android.app.AlertDialog
import android.content.Context.INPUT_METHOD_SERVICE
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.amap.api.location.AMapLocation
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ToastUtils
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity
import com.yicong.ants.R
import com.yicong.ants.databinding.ScenicListFragmentBinding
import com.yicong.ants.scenic.adapter.ScenicListAdapter
import com.yicong.ants.scenic.viewModel.ORDER_LIKE
import com.yicong.ants.scenic.viewModel.ORDER_LOCATION
import com.yicong.ants.scenic.viewModel.ORDER_NORMAL
import com.yicong.ants.scenic.viewModel.ScenicViewModel


class ScenicListFragment : Fragment() {
    private var hasInitializedRootView = false
    private var rootView: View? = null
    private var sort = ORDER_NORMAL
    private lateinit var binding: ScenicListFragmentBinding
    private lateinit var locationPermissionLauncher: ActivityResultLauncher<String>
    private val scenicViewModel: ScenicViewModel by activityViewModels()
    private val adapter = ScenicListAdapter()
    private var position = 0

    val callback = object : LocationUtil.Callback {
        override fun onRequestPermission() {
            AlertDialog.Builder(requireActivity())
                .setView(R.layout.live_common_dialog)
                .show().apply {
                    findViewById<TextView>(R.id.messageTv).text =
                        "“蚁丛”要获取你的地理位置用于展示附近的景区信息以及您与景区的距离信息"
                    findViewById<TextView>(R.id.positiveBtn).setOnClickListener {
                        dismiss()
                        LocationUtil.requestPermission(locationPermissionLauncher)
                    }
                    findViewById<TextView>(R.id.negativeBtn).setOnClickListener {
                        dismiss()

                        scenicViewModel.pCity.value = "广东"
                        scenicViewModel.pChild.value = "深圳"
                    }
                    window?.setBackgroundDrawable(null)
                }
        }

        override fun onLocation(location: AMapLocation) {
            scenicViewModel.pLa = location.latitude.toString()
            scenicViewModel.pLo = location.longitude.toString()
            scenicViewModel.pCity.value = if (location.province.endsWith("省")) {
                location.province.substring(0, location.province.length - 1)
            } else if (location.province.endsWith("市")) {
                location.province.substring(0, location.province.length - 1)
            } else {
                location.province
            }
            scenicViewModel.pChild.value =
                if (location.city.endsWith("市")) location.city.substring(
                    0,
                    location.province.length - 1
                ) else location.city
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        if (rootView != null) {
            return rootView!!
        }
        binding = ScenicListFragmentBinding.inflate(layoutInflater, container, false)
        rootView = binding.root
        return rootView!!
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        scenicViewModel.pChild.observe(viewLifecycleOwner) {
            it?.let {
                binding.txAddress.text = scenicViewModel.pChild.value
                getScenicList()
            }
        }
        scenicViewModel.scenicItemList.observe(viewLifecycleOwner) {
            try {
                it?.bindProgressBar(binding.progressBar)
                    ?.onComplete {
                        it.data?.let { data ->
                            if (refresh) {
                                position = 0
                                adapter.setNewData(arrayListOf())
                            }
                            data.setLoadedCount(adapter.data.size)
                            adapter.addData(it.data?.list ?: arrayListOf())
                            if (data.pageInfo?.curPage == data.pageInfo?.countPage) {
                                adapter.loadMoreEnd()
                            } else {
                                adapter.loadMoreComplete()
                            }
                        }
                    }?.onError(true) {
                        adapter.loadMoreFail()
                    }
            } catch (e: Exception) {
                Log.e("scenicItemList", "" + e.localizedMessage)
            }
            it?.bindProgressBar(binding.progressBar)
                ?.onComplete {
                    it.data?.let { data ->
                        if (refresh) {
                            position = 0
                            adapter.setNewData(arrayListOf())
                        }
                        data.setLoadedCount(adapter.data.size)
                        adapter.addData(it.data?.list ?: arrayListOf())
                        if (refresh) {
                            binding.recyclerView.scrollToPosition(0)
                        }
                        if (data.pageInfo?.curPage == data.pageInfo?.countPage) {
                            adapter.loadMoreEnd()
                        } else {
                            adapter.loadMoreComplete()
                        }
                    }
                }?.onError(true) {
                    adapter.loadMoreFail()
                }
        }
        if (hasInitializedRootView) return
        hasInitializedRootView = true
        BarUtils.setStatusBarLightMode(requireActivity(), false)
        binding.backBtn.setOnClickListener { requireActivity().finish() }
        binding.ruleBtn.setOnClickListener {
            findNavController().navigate(
                ScenicListFragmentDirections.actionScenicListFragmentToScenicRuleFragment()
            )
        }
        binding.locationBtn.setOnClickListener {
            findNavController().navigate(
                ScenicListFragmentDirections.actionScenicListFragmentToScenicLocationFragment()
            )
        }
        binding.orderListBtn.setOnClickListener {
            findNavController().navigate(
                ScenicListFragmentDirections.actionScenicListFragmentToScenicOrderListFragment()
            )
        }
        binding.sortNormalRb.paint.isFakeBoldText = true
        binding.sortRg.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.sortNormalRb -> {
                    binding.sortNormalRb.paint.isFakeBoldText = true
                    binding.sortLikeRb.paint.isFakeBoldText = false
                    binding.sortLocationRb.paint.isFakeBoldText = false
                    sort = ORDER_NORMAL
                    getScenicList()
                }

                R.id.sortLikeRb -> {
                    binding.sortNormalRb.paint.isFakeBoldText = false
                    binding.sortLikeRb.paint.isFakeBoldText = true
                    binding.sortLocationRb.paint.isFakeBoldText = false
                    sort = ORDER_LIKE
                    getScenicList()
                }

                R.id.sortLocationRb -> {
                    binding.sortNormalRb.paint.isFakeBoldText = false
                    binding.sortLikeRb.paint.isFakeBoldText = false
                    binding.sortLocationRb.paint.isFakeBoldText = true
                    sort = ORDER_LOCATION
                    getScenicList()
                }
            }
        }
        locationPermissionLauncher =
            registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
                if (isGranted) {
                    LocationUtil.startLocateOnce(requireContext(), this, callback)
                } else {
                    scenicViewModel.pCity.value = "广东"
                    scenicViewModel.pChild.value = "深圳"

                    ToastUtils.showLong("获取定位失败")
                }
            }
        LocationUtil.startLocateOnce(requireContext(), viewLifecycleOwner, callback)
        adapter.refreshListener = {
            getScenicList()
        }

        binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                position += dy
                if (position > 0) {
                    binding.scrollShadow.isVisible = true
                    binding.sortRg.setBackgroundResource(R.color.white)
                } else {
                    binding.scrollShadow.isVisible = false
                    binding.sortRg.setBackgroundResource(R.color.transparent)
                }
            }
        })
        adapter.bindToRecyclerView(binding.recyclerView)
        adapter.setOnLoadMoreListener {
            getScenicList(false)
        }
        adapter.setOnItemClickListener { _, _, position ->
            findNavController().navigate(
                ScenicListFragmentDirections.actionScenicListFragmentToScenicDetailFragment(
                    adapter.getItem(
                        position
                    )!!.scenicId
                )
            )
        }

        binding.eTxSearch.setOnEditorActionListener { textView, i, keyEvent ->
            if (i == EditorInfo.IME_ACTION_SEND || (keyEvent != null && keyEvent.keyCode == KeyEvent.KEYCODE_ENTER)) {
                if (keyEvent.action == KeyEvent.ACTION_UP) {
                    //收回软键盘
                    val imm =
                        requireActivity().getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                    imm.hideSoftInputFromWindow(requireActivity().window.decorView.windowToken, 0)
                    //关键字搜索
                    getScenicList()
                }
                return@setOnEditorActionListener true
            }
            false
        }

    }

    private var refresh = true
    private fun getScenicList(refresh: Boolean = true) {
        this.refresh = refresh
        scenicViewModel.getScenicList(
            requireActivity() as BaseTitleBarActivity<*>,
            keyword = binding.eTxSearch.text.toString(),
            sort = sort,
            refresh = refresh,
            cityName = scenicViewModel.pChild.value,
            provinceName = scenicViewModel.pCity.value,
            longitude = scenicViewModel.pLo,
            latitude = scenicViewModel.pLa
        )
    }
}